#!/usr/bin/env python
#encoding: utf-8
#功能：nagios插件, 实现检测系统Free内存数量

import sys
from optparse import OptionParser

# 定义了单位的相关字典
unit = {'b':1, 'k':2**10, 'm':2**20, 'g':2**30, 't':2**40}

# 解析命令行选项的函数
def opt():
    parser = OptionParser('Usage: %prog [-w WARNING] [-c CRITICAL]')
    parser.add_option('-w', dest='warning', action='store', default='100M', help='WARNING') 
    parser.add_option('-c', dest='critical', action='store', default='50M', help='CRITICAL') 
    options, args = parser.parse_args()
    # 返回解析出的选项和参数
    return options, args

# 获取系统剩余内存输出单位MB
def getFreeMemory():
    with open('/proc/meminfo') as fd:
        for line in fd:
            if line.startswith('MemFree'):
                mem = line.split()[1].strip()
                break
    # 以字节为单位返回
    return int(mem) * 1024

# 将给定的字符串计算为以字节为单位的数值
def scaleUnit(s):
    lastchar = s[-1]
    lastchar = lastchar.lower()
    num = float(s[:-1])
    if lastchar in unit:
        return num * unit[lastchar]
    else:
        return int(s)

# 将输入参数(字节数)转换为适合单位(K,M,G)输出返回
def changeUnit(byte):
    for k,v in unit.items():
        num = float(byte)/v
        if 0 < num <= 1024:
            num = '%.2f' % num    # 保留2位小数
            result = str(num) + k.upper()    # 输出比如，1.72G
    return result

# 程序的主函数
def main():
    options, args = opt()
    w = scaleUnit(options.warning)
    c = scaleUnit(options.critical)
    mem = getFreeMemory()
    human_readable_unit = changeUnit(mem)

    # 根据参数判断是否是w或c或ok或un
    if mem > w:
        print 'OK', human_readable_unit
        sys.exit(0)
    elif mem > c and mem <= w:
    #elif c < mem <= w:
        print 'WARNING', human_readable_unit
        sys.exit(1)
    elif mem < c:
        print 'CRITICAL', human_readable_unit
        sys.exit(2)
    else:
        print 'UNKNOWN', human_readable_unit
        sys.exit(3)


# run
if __name__ == '__main__':
    main()

